package com.sjy.ylxt.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class MD5Util {

    /**
     * 对输入字符串进行MD5加密。
     *
     * @param input 要加密的字符串
     * @return 加密后的16进制字符串表示
     */
    public static String encryptToMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));

            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);

            // 确保长度为32位，前面补0
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }

            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Algorithm not found: MD5", e);
        }
    }

    /**
     * 验证提供的字符串是否与存储的MD5哈希值匹配。
     *
     * @param providedInput 用户提供的字符串
     * @param storedHash 存储的MD5哈希值
     * @return 如果提供的字符串匹配存储的哈希值，则返回true；否则返回false
     */
    public static boolean verifyMD5(String providedInput, String storedHash) {
        String newHash = encryptToMD5(providedInput);
        return newHash.equals(storedHash);
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        String password = "your_password_here"; // 要加密的字符串

        // 创建MD5哈希并存储
        String hashedPassword = encryptToMD5(password);
        System.out.println("Original: " + password);
        System.out.println("MD5: " + hashedPassword);

        // 验证密码
        String providedPassword = "your_password_here"; // 用户提供的密码
        boolean isVerified = verifyMD5(providedPassword, hashedPassword);
        System.out.println("Password verified: " + isVerified);

        // 尝试使用错误的密码
        String wrongPassword = "wrong_password";
        boolean isWrongVerified = verifyMD5(wrongPassword, hashedPassword);
        System.out.println("Wrong password verified: " + isWrongVerified);
    }
}